<?php

namespace app\admin\controller;
use app\admin\logic\GoodsLogic;
use think\AjaxPage;
use think\Page;
use think\Db;

class Destine extends Base {
    
    private $limit = 10;
    /**
     *  商品列表
     */
    public function goodsList(){                
     
        $GoodsLogic = new GoodsLogic();        
        $brandList = $GoodsLogic->getSortBrands();
        $categoryList = $GoodsLogic->getSortCategory();
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);
        return $this->fetch();

    }
    
    /**
     *  ajax请求商品列表
     */
    public function ajaxGoodsList(){            
        
        $where = ' 1 = 1 '; // 搜索条件                
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;        
        I('brand_id') && $where = "$where and brand_id = ".I('brand_id') ;
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale') ;                
        $cat_id = empty(I('cat_id'))?0:I('cat_id');
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
        
        if($cat_id > 0)
        {
            $grandson_ids = getCatGrandson($cat_id); 
            $where .= " and cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
        }
        
        
        $model = M('Goods');
        $where = "$where and type = 2";//只查询定制产品
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        /**  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        */
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();

        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        return $this->fetch();
    }
    
	/**
     *  添加定制商品
     */
    public function addeditGoods(){
    	$GoodsLogic = new GoodsLogic();
        $Goods = D('Goods');
		if(I('id')&&is_numeric(I('id'))){
				$goods_id = I('id');
				$g1 = M('goods')->where(array('goods_id'=>$goods_id))->find();
				$g2 = M('destine_goods_attr')->where(array('goods_id'=>$goods_id))->find();
				if($g2){
					$g2['honor_images'] = json_decode($g2['honor_images'],true);//转换荣誉图片
					$g2['quantity'] = json_decode($g2['quantity'],true);//转换荣誉图片
					$g2['tmp_info'] = json_decode($g2['tmp_info'],true);
				}
				$goodsInfo = array_merge($g1,$g2);
				$this->assign('goodsInfo',$goodsInfo);
		}
    	if(IS_POST){
    	    // 数据验证
    	    $validate = \think\Loader::validate('DestineGoods');
    	    if(!$validate->batch()->check(input('post.')))
    	    {
    	        $error = $validate->getError();
    	        $error_msg = array_values($error);
    	        $return_arr = array(
    	            'status' => -1,
    	            'msg' => $error_msg[0],
    	            'data' => $error,
    	        );
    	        $this->ajaxReturn($return_arr);
    	    }else{
        		$data = I('post.'); 
    			//拆分数据
    			array_pop($data['honor_images']);
    			$data1 = array(//destine_goods_attr附属表数据
    			       'theme_id' => $data['theme_id'],
    			       'aroma_id' => $data['aroma_id'],
    			       'winery_id' => $data['winery_id'],
    			       'degree' => $data['degree'],
    			       'years' => $data['years'],
    			       'quantity' => empty($data['quantity'])?'':json_encode($data['quantity']),
    			       'material' => $data['material'],
    			       'productiontime' => strtotime($data['productiontime']),
    			       'bar_code' => $data['bar_code'],
    			       'licence_code' => $data['licence_code'],
    			       'grade' => $data['grade'],
    			       'd_start' => $data['d_start'],
				       'd_end' => $data['d_end'],
				       'is_sample' => $data['is_sample'],
				       'tmp_info' => json_encode($data['tmp_info']),
				       'honor_images' => empty($data['honor_images'])?'':json_encode($data['honor_images']),   
				); 
				$data2 = array(//goods主表数据
				       'goods_name' => $data['goods_name'],
				       'goods_sn' => $data['goods_sn'],
    			       'shop_price' => $data['shop_price'],
    			       'market_price' => $data['market_price'],
    			       'give_integral' => $data['give_integral'],
    			       'store_count' => $data['store_count'],
    			       'original_img' => $data['original_img'],
    			       'keywords' => $data['keywords'],
				       'weight' =>$data['weight'],
    			       'goods_content' => $data['goods_content'],
    			       'is_distribut' => $data['is_distribut'],
    			       'deduction_amount' => $data['deduction_amount'],
    			       'last_update' => time(),
    			       'suppliers_id' => $data['winery_id'],
    			       'exchange_integral' => $data['d_end'],
    			       'type' => 2,
    			       'shipping_area_ids' => implode(',',I('shipping_area_ids/a',[])),
    			       
    			); 
    			if($goods_id){
    				M('goods')->where(array('goods_id'=>$goods_id))->save($data2);
    				M('destine_goods_attr')->where(array('goods_id'=>$goods_id))->save($data1);
    				// 修改商品后购物车的商品价格也修改一下
                    M('cart')->where("goods_id = $goods_id and spec_key = ''")->save(array(
                            'market_price'=>I('market_price'), //市场价
                            'goods_price'=>I('shop_price'), // 本店价
                            'member_goods_price'=>I('shop_price'), // 会员折扣价                        
                            ));            
    			}else{
    				$data2['on_time'] = time();//上架时间
    				M('goods')->add($data2); // 写入数据到数据库                   
                    $data1['goods_id'] = $goods_id = M('goods')->getLastInsID();
    				M('destine_goods_attr')->add($data1);   
    			}  
    			$Goods->afterSave($goods_id);//处理商品图片
                $return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/goodsList')),
                );
    	    	return  $this->ajaxReturn($return_arr); 
    		}	   
    	}        

        $theme = M('destine_theme')->field('id,title')->select();//定制主题
		$aroma = M('destine_aroma')->field('id,title')->select();//香型
		$quantity = M('destine_quantity')->field('id,val')->select();//净含量规格
		$suppliers = M('suppliers')->field('suppliers_id,suppliers_name')->select();//原产地酒厂
		$destmp = M('destmp')->where('status',1)->select();//定制模板
        $this->assign('theme',$theme);
		$this->assign('aroma',$aroma);
		$this->assign('quantity',$quantity);
		$this->assign('suppliers',$suppliers);
		$this->assign('destmp',$destmp);
		$plugin_shipping = M('plugin')->where(array('type'=>array('eq','shipping')))->select();//插件物流
        $shipping_area = D('Shipping_area')->getShippingArea();//配送区域
        $goods_shipping_area_ids = explode(',',$goodsInfo['shipping_area_ids']);
        $goodsImages = M("GoodsImages")->where(array('goods_id'=>$goods_id))->select();
        $this->assign('goodsImages', $goodsImages);  // 商品相册
		$this->assign('goods_shipping_area_ids',$goods_shipping_area_ids);
        $this->assign('shipping_area',$shipping_area);
        $this->assign('plugin_shipping',$plugin_shipping);
		
        return $this->fetch();            

    }
	
	
	/**
     *  删除定制商品
     */
    /**
     * 删除商品
     */
    public function delGoods()
    {
        $goods_id = $_GET['id'];
        $error = '';
        
        // 判断此商品是否有订单
        $c1 = M('OrderGoods')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有订单,不得删除! <br/>';
         
        
         // 商品退货记录
        $c1 = M('return_goods')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有退货记录,不得删除! <br/>';
        
        if($error)
        {
            $return_arr = array('status' => -1,'msg' =>$error,'data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
            $this->ajaxReturn($return_arr);
        }
        
        // 删除此商品        
        M("Goods")->where('goods_id ='.$goods_id)->delete();  //商品表
        M("cart")->where('goods_id ='.$goods_id)->delete();  // 购物车
        M("comment")->where('goods_id ='.$goods_id)->delete();  //商品评论
        M("goods_consult")->where('goods_id ='.$goods_id)->delete();  //商品咨询
        M("goods_images")->where('goods_id ='.$goods_id)->delete();  //商品相册
        M("spec_goods_price")->where('goods_id ='.$goods_id)->delete();  //商品规格
        M("spec_image")->where('goods_id ='.$goods_id)->delete();  //商品规格图片
        M("goods_attr")->where('goods_id ='.$goods_id)->delete();  //商品属性     
        M("goods_collect")->where('goods_id ='.$goods_id)->delete();  //商品收藏    
        M("destine_goods_attr")->where('goods_id ='.$goods_id)->delete();  //定制商品属性       
                     
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
        $this->ajaxReturn($return_arr);
    }
	
	
    /**
     *  定制主题
     */
    public function desTheme(){                
        $model = M('destine_theme');
        $page = empty(I("post.p"))?1:I("post.p");
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        $themesList = $model->limit(($page-1)*$this->limit,$this->limit)->order("id desc")->select();
        $this->assign('pager',$Page->show());
        $this->assign('themeList',$themesList);
        return $this->fetch();
    }
    
    /**
     *  添加更新定制主题
     */
    public function addeditTheme(){ 
    	    	
    	$model = M('destine_theme');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	$res = $model->where(array('id'=>$id))->find();
        	$this->assign('theme',$res);
        }
    	if(IS_POST){
    		$data = I('post.');
    		if(empty(I('post.title'))){
    		    $return_arr = array(
    		        'status' => -1,
    		        'msg' => '主题名不能为空',
    		        'data' => '主题名不能为空',
    		    );
    		    return  $this->ajaxReturn($return_arr);
    		}
    		if($id){
    			$data['edittime'] = time();
    			$msg = $model->where(array('id'=>$id))->save($data);
    		}else{
    			$data['addtime'] = time();
    		    $data['edittime'] = time();
    		    $msg = $model->add($data);
    		}
    	    if($msg){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/desTheme')),
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	    else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '数据入库失败，请联系系统管理员',
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	}else{
    		return $this->fetch();
    	}             
    }
    
    /**
     *  删除定制主题
     */
    public function delTheme(){ 
    	    	
    	$model = M('destine_theme');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	if($model->where(array('id'=>$id))->delete()){
        		$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/desTheme')),
                );
    	    	return  $this->ajaxReturn($return_arr);
        	}else{
        		$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '删除数据失败，请联系管理员！',
                );
    	    	return  $this->ajaxReturn($return_arr);
        	}
        }
        else{
        	$return_arr = array(
                    'status' => -1,
                    'msg' => '参数错误，请不要非法操作！',
                    'data' => array('url' => U('admin/destine/desTheme')),
                );
    	    	return  $this->ajaxReturn($return_arr);
        }
    	             
    }
    
    
    /**
     *  白酒香型
     */
    public function desAroma(){ 
    	$model = M('destine_aroma');
    	$page = empty(I("post.p"))?1:I("post.p");
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        $aromaList = $model->limit(($page-1)*$this->limit,$this->limit)->order("id desc")->select();
        $this->assign('pager',$Page->show());
        $this->assign('aromaList',$aromaList);
        return $this->fetch();               
    }
    
    /**
     *  添加更新白酒香型
     */
    public function addeditAroma(){ 
    	    	
    	$model = M('destine_aroma');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	$res = $model->where(array('id'=>$id))->find();
        	$this->assign('aroma',$res);
        }
    	if(IS_POST){
    		$data = I('post.');
    		if(empty(I('post.title'))){
    		    $return_arr = array(
    		        'status' => -1,
    		        'msg' => '香型名称不能为空',
    		        'data' => '香型名称不能为空',
    		    );
    		    return  $this->ajaxReturn($return_arr);
    		}
    		if($id){
    			$msg = $model->where(array('id'=>$id))->save($data);
    		}else{
    			$data['addtime'] = time();
    		    $msg = $model->add($data);
    		}
    	    if($msg){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/desAroma')),
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	    else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '数据入库失败，请联系系统管理员',
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	}else{
    		return $this->fetch();
    	}             
    }
    

    /**
     *  删除白酒香型
     */
    public function delAroma(){ 
    	    	
    	$model = M('destine_aroma');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	if($model->where(array('id'=>$id))->delete()){
        		$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/desAroma')),
                );
    	    	return  $this->ajaxReturn($return_arr);
        	}else{
        		$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '删除数据失败，请联系管理员！',
                );
    	    	return  $this->ajaxReturn($return_arr);
        	}
        }
        else{
        	$return_arr = array(
                    'status' => -1,
                    'msg' => '参数错误，请不要非法操作！',
                    'data' => array('url' => U('admin/destine/desAroma')),
                );
    	    	return  $this->ajaxReturn($return_arr);
        }
    	             
    }        
    
    
    
    
   
    /**
     *  最新活动管理
     */
    public function newActivity(){
    	$model = M('destine_activity');
    	$page = empty(I("post.p"))?1:I("post.p");
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        $res = $model->limit(($page-1)*$this->limit,$this->limit)->order("id desc")->select();
        $this->assign('pager',$Page->show());
        $this->assign('activitys',$res);                    
        return $this->fetch();
    }
    
    
    /**
     *  添加更新最新活动
     */
    public function addeditActivity(){ 
    	    	
    	$model = M('destine_activity');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	$res = $model->where(array('id'=>$id))->find();
        	$this->assign('activity',$res);
        }
    	if(IS_POST){
    		$data = I('post.');
    		if(empty(I('post.title'))){
    		    $return_arr = array(
    		        'status' => -1,
    		        'msg' => '活动标题不能为空',
    		        'data' => '活动标题不能为空',
    		    );
    		    return  $this->ajaxReturn($return_arr);
    		}elseif (empty(I('post.acurl'))){
    		    $return_arr = array(
    		        'status' => -1,
    		        'msg' => '活动链接不能为空',
    		        'data' => '活动链接不能为空',
    		    );
    		    return  $this->ajaxReturn($return_arr);
    		}
    		$data['publishtime'] = strtotime($data['publishtime']);
    		$data['starttime'] = strtotime($data['starttime']);
    		$data['endtime'] = strtotime($data['endtime']);
    		if($id){
    			$msg = $model->where(array('id'=>$id))->save($data);
    		}else{
    			$data['addtime'] = time();
    		    $msg = $model->add($data);
    		}
    	    if($msg){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/newActivity')),
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	    else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '数据入库失败，请联系系统管理员',
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	}else{
    		return $this->fetch();
    	}             
    }
    
    
    /**
     *  删除最新活动
     */
    public function delActivity(){ 
    	    	
    	$model = M('destine_activity');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	if($model->where(array('id'=>$id))->delete()){
        		$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/newActivity')),
                );
    	    	return  $this->ajaxReturn($return_arr);
        	}else{
        		$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '删除数据失败，请联系管理员！',
                );
    	    	return  $this->ajaxReturn($return_arr);
        	}
        }
        else{
        	$return_arr = array(
                    'status' => -1,
                    'msg' => '参数错误，请不要非法操作！',
                    'data' => array('url' => U('admin/destine/newActivity')),
                );
    	    	return  $this->ajaxReturn($return_arr);
        }
    	             
    } 
    
    
    /**
     *  净含量规格
     */
    public function desQuantity(){                
        $model = M('destine_quantity');
        $page = empty(I("post.p"))?1:I("post.p");
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        $res = $model->limit(($page-1)*$this->limit,$this->limit)->order("id desc")->select();
        $this->assign('pager',$Page->show());
        $this->assign('quantityList',$res);
        return $this->fetch();
    }
    
    /**
     *  添加更新定制方式
     */
    public function addeditQuantity(){ 
    	    	
    	$model = M('destine_quantity');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	$res = $model->where(array('id'=>$id))->find();
        	$this->assign('destinequantity',$res);
        }
    	if(IS_POST){
    		$data = I('post.');
    		if(empty(I('post.val'))){
    		    $return_arr = array(
    		        'status' => -1,
    		        'msg' => '净含量规格不能为空',
    		        'data' => '净含量规格不能为空',
    		    );
    		    return  $this->ajaxReturn($return_arr);
    		}
    		if($id){
    			$msg = $model->where(array('id'=>$id))->save($data);
    		}else{
    		    $msg = $model->add($data);
    		}
    	    if($msg){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/desQuantity')),
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	    else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '数据入库失败，请联系系统管理员',
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	}else{
    		return $this->fetch();
    	}             
    }    
    
    
    
    /**
     *  删除净含量
     */
    public function delQuantity(){ 
    	    	
    	$model = M('destine_quantity');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	if($model->where(array('id'=>$id))->delete()){
        		$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/desQuantity')),
                );
    	    	return  $this->ajaxReturn($return_arr);
        	}else{
        		$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '删除数据失败，请联系管理员！',
                );
    	    	return  $this->ajaxReturn($return_arr);
        	}
        }
        else{
        	$return_arr = array(
                    'status' => -1,
                    'msg' => '参数错误，请不要非法操作！',
                    'data' => array('url' => U('admin/destine/desQuantity')),
                );
    	    	return  $this->ajaxReturn($return_arr);
        }
    	             
    }
    
    
    /**
     *  净含量规格
     */
    public function destmp(){                
        $model = M('destmp');
        $page = empty(I("post.p"))?1:I("post.p");
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        $res = $model->limit(($page-1)*$this->limit,$this->limit)->order("id desc")->select();
        $this->assign('pager',$Page->show());
        $this->assign('destmp',$res);
        return $this->fetch();
    }
    
    /**
     *  添加更新定制方式
     */
    public function addeditTmp(){ 
    	    	
    	$model = M('destmp');
        
        //若获取到ID则表示编辑，否则视为新增
        if(I('id')&&is_numeric(I('id'))){
        	$id = I('id');
        	$res = $model->where(array('id'=>$id))->find();
        	$this->assign('destmp',$res);
        }
    	if(IS_POST){
    		$data = I('post.');
    		if(empty(I('post.title'))){
    		    $return_arr = array(
    		        'status' => -1,
    		        'msg' => '模板标题不能为空',
    		        'data' => '模板标题不能为空',
    		    );
    		    return  $this->ajaxReturn($return_arr);
    		}elseif (empty(I('post.url'))){
    		    $return_arr = array(
    		        'status' => -1,
    		        'msg' => '模板链接不能为空',
    		        'data' => '模板链接不能为空',
    		    );
    		    return  $this->ajaxReturn($return_arr);
    		}
    		if($id){
    			$msg = $model->where(array('id'=>$id))->save($data);
    		}else{
    		    $msg = $model->add($data);
    		}
    	    if($msg){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/destine/destmp')),
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	    else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => '数据入库失败，请联系系统管理员',
                );
    	    	return  $this->ajaxReturn($return_arr);
    	    }
    	}else{
    		return $this->fetch();
    	}             
    }    
    
}